# coding：utf-8
import datetime
from lxml import etree
from openpyxl import load_workbook
from header_maker import HEADER_MAKER
from selenium.webdriver import FirefoxOptions, Firefox
from selenium.webdriver.firefox.service import Service
from DB_OPERTER import DB
from PyQt5.QtCore import pyqtSignal, QThread

class Browser(QThread):
    # label_signal = pyqtSignal(str)
    def __init__(self, parent=None):
        super(Browser, self).__init__(parent)
        self.url = ""
        option = FirefoxOptions()
        option.binary_location = r'C:/Program Files/Mozilla Firefox/firefox.exe'
        driverService = Service('./geckodriver')
        self.driver = Firefox(service=driverService, options=option)
        # self.driver.set_window_size(1920 / 1.25, 1080 / 1.25)

    def run(self):
        # 作为预写入内容
        # self.driver.get(self.url)
        self.driver.set_window_size(1920 / 1.25, 1080 / 1.25)
        # time.sleep(1)
        self.driver.minimize_window()
        self.driver.get(self.url)


class P6_V_H(QThread):
    label_signal = pyqtSignal(str, int, int)

    def __init__(self, parent=None):
        super(P6_V_H, self).__init__(parent)
        self.HE = HEADER_MAKER()
        self.img_headers = self.HE.img_header_18_H
        self.DB = DB()
        option = FirefoxOptions()
        option.add_argument('--headless')
        option.set_preference('permissions.default.image', 2)
        option.page_load_strategy = 'eager'
        option.binary_location = r'C:/Program Files/Mozilla Firefox/firefox.exe'
        driverService = Service('./geckodriver')
        self.driver = Firefox(service=driverService, options=option)

    def make_log(self, text, now, all_):
        #     with open("./log.txt", "a") as file:
        #         file.write(text)
        #         file.write("\n")
        self.label_signal.emit(text, now, all_)
        # print(text, now, all_)

    def selenium_content(self, url):
        self.driver.get(url)
        content = self.driver.page_source
        return content

    def selenium_doors(self, url):

        content = self.selenium_content(url)
        # print(content)

        tree = etree.HTML(content)

        li_list = tree.xpath('/html/body/div/div/div[3]/div[6]/div[2]/div[2]/div[2]/ul/table')
        # print("li_list", li_list)
        list_ = []
        for li in li_list:
            href = li.xpath('tbody/tr[2]/td[2]/b/a/@href')[0]
            title_ori = li.xpath('tbody/tr[2]/td[2]/b/a/@title')
            # print("title_ori", title_ori)
            if title_ori.__len__() > 0:
                title = title_ori[0]

            else:
                title = li.xpath('a/font/text()')[0]
            # print("href", href)
            # print("title", title)
            list_.append(["https://www.dy2018.com/" + href, title.replace("'", "")])

        return list_

    def run(self):

        self.make_log("start", 1, 100)
        wb = load_workbook("./list_dytt.xlsx")
        sh = wb["list"]

        for page in range(2, 8):

            class_ = sh.cell(page, 4).value
            if sh.cell(page, 1).value != "":
                url_base = sh.cell(page, 1).value
                start = int(sh.cell(page, 2).value)
                end = int(sh.cell(page, 3).value)
                range_ = end - start
                print(url_base, start, end, range_, sh.cell(page, 4).value)
                for i in range(start, end + 1):
                    now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
                    url = url_base + "_{}.html".format(i)
                    list_ = self.selenium_doors(url)
                    for l in list_:
                        if self.DB.Check_Repeat_url(l[0]):
                            self.make_log("{}\t{}\t{}\t已存在:\t{}".format(class_, now, i, l[0]), i - start + 1, range_)
                        else:
                            self.make_log("{}\t{}\t{}\t输入中:\t{}".format(class_, now, i, l[0]), i - start + 1, range_)
                            self.DB.insert_url(class_, l[0], l[1])
                    self.DB.commit_it()

        self.driver.quit()
        wb.save("./list_dytt.xlsx")
        self.make_log("完成", 100, 100)

    def stop(self):
        self.terminate()
        self.make_log("线程停止!", 100, 100)
    # def selenium_doors(self, url):
    #     content = requests.get(url, headers=self.img_headers)
    #     tree = etree.HTML(content.text)
    #     # tree = etree.HTML(content)
    #     li_list = tree.xpath('/html/body/div[4]/div[1]/div/ul/li')

    #     list_ = []
    #     for li in li_list:
    #         href = li.xpath('a/@href')[0]
    #         title_ori = li.xpath('a/text()')
    #         # print("title_ori", title_ori)
    #         if title_ori.__len__() > 0:
    #             title = title_ori[0].encode("iso-8859-1").decode('gbk').encode('utf8').decode('utf8')

    #         else:
    #             title = li.xpath('a/font/text()')[0].encode("iso-8859-1").decode('gbk').encode('utf8').decode('utf8')
    #         # print("href", href)
    #         # print("title", title)
    #         list_.append(["https://www.hao6v.tv" + href, title.replace("'", "")])

    #     return list_


# if __name__ == '__main__':
    # P6_V_H()

    # wb = load_workbook("./list_18_H.xlsx")
    # sh = wb["list"]
    # file_path = []
    # for i in range(sh.max_row - 1):

    #     V6.make_log(str(sh.cell(i + 2, 5).value) + "\t\t\t\t\t\t\t\t\t" + str(sh.cell(i + 2, 1).value))
    #     if sh.cell(i + 2, 5).value == None:
    #         V6.url = sh.cell(i + 2, 2).value
    #         V6.path = "./_IMAGES_/" + "18_H_" + sh.cell(i + 2, 1).value + "/"
    #         href_list, file_paths, img_count = V6.selenium_doors()

    #         start, end = int(sh.cell(i + 2, 3).value), int(sh.cell(i + 2, 4).value) + 1
    #         V6.get_imgs(start, end, href_list, file_paths, img_count)
    #         sh.cell(i + 2, 5).value = "已下载"
    #     wb.save("./list_18_H.xlsx")
